package com.sise.rsc.controller;

import com.sise.rsc.bean.Result;
import com.sise.rsc.entity.*;
import com.sise.rsc.repository.CourierRepository;
import com.sise.rsc.repository.PackageActionRepository;
import com.sise.rsc.service.*;
import com.sise.rsc.util.CacheUtil;
import com.sise.rsc.util.RandomUtil;
import com.sise.rsc.util.TimeUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.OptionalInt;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;
    @Resource
    private RoleService roleService;
    @Resource
    private UserService userService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private PackageService packageService;
    @Resource
    private CourierService courierService;
    @Resource
    private TaskService taskService;
    @Resource
    private PackageActionRepository packageActionRepository;

    //管理员主页面
    @RequestMapping("/index")
    public String index(){
        return "admin/index";
    }
    //添加快递员的视图
    @RequestMapping("/addCourierView")
    public String addCourier(Model model){
        //查询所有工作区域
        List<WorkingArea> workingAreas = adminService.findAllWorkingArea();
        //如果没有工作区域，则重定向到添加工作区域界面
        if (workingAreas.isEmpty())
            return "redirect:admin/addWorkingAreaView";
        //加入model
        model.addAttribute("workingAreas",workingAreas);
        return "admin/add-courier";
    }
    //添加快递员
    @RequestMapping("/addCourier")
    @ResponseBody
    public Result addCourier(String name, String phone, String username, String password, String address, String sex, String workingAreaId){

        User user0 = userService.findUserByUsername(username);
        if (user0!=null)
            return new Result(500,"登录名称已经存在！");


//        {"realName":"cailong ","phone":"1343434","username":"123","password":"456","address":"华软","sex":"男","workingAreaId":"2"}
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setPhone(phone);

        Role role = roleService.findRoleByAuthority("ROLE_KD");
        if (role == null){
            role = new Role("ROLE_KD");
            roleService.save(role);
        }
        List<Role> roles = new LinkedList<>();
        roles.add(role);
        user.setRoles(roles);
        userService.save(user);

        Courier courier = new Courier();
        String no;
        while (true){
            no ="Y"+ RandomUtil.getRandomNumber(4);
            if (adminService.findCourierByNo(no) ==null)
                break;
        }
        courier.setNo(no);
        courier.setRealName(name);
        courier.setSex(sex);
        WorkingArea workingArea = adminService.findWorkingAreaById(Integer.parseInt(workingAreaId));
        if (workingArea == null)
            return new Result(500,"工作区域错误！");
        courier.setWorkingArea(workingArea);
        courier.setAddress(address);
        courier.setUser(userService.findUserByUsername(username));


        adminService.addCourier(courier);
        return new Result(200,"处理成功！");
    }
    //展示快递员列表
    @RequestMapping("/listCourierView")
    public String listCourier(Model model){
        //查询所有快递员信息
        List<Courier> courierList = adminService.listCourier();
        //如果没有快递员，则重定向到添加快递员界面
        if (courierList.isEmpty())
            return "redirect:admin/addCourierView";
        //加入model
        model.addAttribute("courierList",courierList);
        return "admin/list-couriers";
    }
    //添加工作区域的视图
    @RequestMapping("/addWorkingAreaView")
    public String addWorkingArea(){
        return "admin/add-working-area";
    }

    //添加工作区域
    @RequestMapping("/addWorkingArea")
    @ResponseBody
    public Result addWorkingArea(String address){

        if (address.equals(""))
            return new Result(500,"地址信息不能为空！");

        WorkingArea workingArea = adminService.findWorkingAreaByAddressName(address);

        if (workingArea != null)
            return new Result(500,"地址["+address+"]已存在，请重新输入！");
        else {

            workingArea = new WorkingArea();
            workingArea.setAddressName(address);
            adminService.addWorkingAres(workingArea);
            return new Result(200,"地址信息添加成功！");
        }



    }
    //展示工作区列表
    @RequestMapping("/listWorkingArea")
    public String listWorkingArea(Model model){
        //查询所有快递员信息
        List<WorkingArea> workingAreas = adminService.findAllWorkingArea();
        //如果没有快递员，则重定向到添加快递员界面
        if (workingAreas.isEmpty())
            return "redirect:admin/addWorkingAreaView";
        //加入model
        model.addAttribute("workingAreas",workingAreas);
        return "admin/list-workingArea";
    }
    //显示订单列表
    @RequestMapping("/listPackage")
    public String listPackage(){

        return "admin/list-package";
    }
    //查找所有包裹
    @RequestMapping(value = "/findAllAPackage")
    @ResponseBody
    public String findAllAPackage(){
        String  jsonStr = packageService.findAllAPackageToJson();
        return jsonStr;
    }
    //展示快递员所有工作信息以及工作量
    @RequestMapping("/courierWorkNum")
    public String courierWorkNum(Model model){
        List<Task> taskList = taskService.findAllTaskByState();//state=1
        //查询所有快递员信息
        List<Courier> courierList = adminService.listCourier();
        //如果没有快递员，则重定向到添加快递员界面
        if (courierList.isEmpty())
            return "redirect:admin/addCourierView";
        //加入model
        model.addAttribute("courierList",courierList);
        model.addAttribute("taskList",taskList);

        return "admin/list-work-num";
    }
    //展示快递员所有工作信息以及工作量细节
    @RequestMapping("/courierWorkNumDetailBycId")
    public String courierWorkNumDetail(Model model,int cId){
        int taskNum = taskService.findAllTaskByStateAndcId(cId);//state=1
        //查询快递员信息
        Courier courier = adminService.listCourierBycId(cId);
        //加入model
        model.addAttribute("courier",courier);
        model.addAttribute("taskNum",taskNum);
        model.addAttribute("salary",taskNum*0.8+1500);

        return "admin/list-work-num-detail";
    }

    //查找某一个快递员当月的派件量
    @RequestMapping(value = "/getThisMonthFetchNum")
    @ResponseBody
    public int getThisMonthFetchNum(int courierId){
        Courier courier=courierService.findCourierByUserId(courierId);
        return courierService.getThisMonthFetchNumByCourierId(courier.getId());
    }
    //查找某一个快递员当月的派件量
    @RequestMapping(value = "/getThisMonthDeliverNum")
    @ResponseBody
    public int getThisMonthDeliverNum(int courierId){
        Courier courier=courierService.findCourierByUserId(courierId);
        return courierService.getThisMonthDeliverNumByCourierId(courier.getId());
    }

    @RequestMapping("/package/{state}")
    public String packageState(@PathVariable int state,Model model){

        List<APackage> aPackages = packageService.findAPackagesByState(state);

        model.addAttribute("packages",aPackages);
        if (state == 2)
            return "admin/list-package-2";

        return "error";


    }

    /**
     * 改变包裹的状态
     * @param pNo
     * @param state
     * @return
     */
    @RequestMapping("/changePackageState")
    @ResponseBody
    public Object changePackageState(String pNo,int state){

        packageService.updateAPackageStateByNo(state,pNo);
        APackage aPackage = packageService.findAPackageByNo(pNo);
        if (aPackage != null){
            //packageAction
            PackageAction packageAction = new PackageAction();
            packageAction.setaPackage(aPackage);
            packageAction.setCourier(courierService.findCourierByUserId(3));
            packageAction.setState(aPackage.getState());
            packageAction.setTime(new Date());
            packageAction.setAction("快件已经到达目的地【"+aPackage.getReceiptAddress()+"】");
            packageActionRepository.save(packageAction);



            //派件分配
            if (TimeUtil.belongCalendarIn6To18()){//判断是否在工作时间，是则分配派件，

                if (taskService.AssignTasks(aPackage,"派件")){
                    System.out.println("pno" + pNo + "成功分配派件员");
                }else{

                    //判断是否可以自动分配
                    if (taskService.isCanAutoAssignTasks(aPackage.getReceiptAddress()))
                        CacheUtil.packageDeliverAutoList.add(pNo);
                }
            }else {//否则隔日分配

                CacheUtil.packageDeliverNextDayList.add(pNo);
            }
        }


        return "ok";
    }






}
